/**
 * Copyright 2014  XCL-Charts
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @Project XCL-Charts
 * @Description Android图表基类库
 * @author XiongChuanLiang<br></br>(xcl_168@aliyun.com)
 * @Copyright Copyright (c) 2014 XCL-Charts (www.xclcharts.com)
 * @license http://www.apache.org/licenses/  Apache v2 License
 * @version 1.0
 */
package com.demo.xclcharts.view1

import android.annotation.SuppressLint
import android.content.Context
import android.graphics.Color
import android.util.AttributeSet
import android.util.Log
import android.view.MotionEvent
import com.gitee.wsl.common.chart.ChartEnum
import com.gitee.wsl.common.chart.sample.pie.PieChart
import com.gitee.wsl.common.chart.sample.pie.model.PieData
import com.gitee.wsl.common.ui.draw.type.HorizontalAlign
import com.gitee.wsl.common.ui.draw.type.VerticalAlign
import org.xclcharts.common.DensityUtil
import timber.log.Timber

/**
 * @ClassName PieChart01View
 * @Description  饼图的例子
 * @author XiongChuanLiang<br></br>(xcl_168@aliyun.com)
 */
class PieChart01View : DemoView, Runnable {
    private val TAG = "PieChart01View"
    private val chart = PieChart()
    private val chartData = ArrayList<PieData>()
    private var mSelectedID = -1

    constructor(context: Context) : super(context) {
        // TODO Auto-generated constructor stub
        initView()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(
        context, attrs
    ) {
        initView()
    }

    constructor(context: Context, attrs: AttributeSet?, defStyle: Int) : super(
        context, attrs, defStyle
    ) {
        initView()
    }

    private fun initView() {
        chartDataSet()
        chartRender()

        //綁定手势滑动事件
        this.bindTouch(this, chart)
        //Thread(this).start()
        chart.addSelectListener{
            Timber.d("call listen on select object $it")
        }
    }


    private fun chartRender() {
        try {

            //设置绘图区默认缩进px值
            val ltrb = pieDefaultSpadding
            val right = DensityUtil.dip2px(context, 100f).toFloat()
            /*chart.setPadding(ltrb[0].toFloat(), ltrb[1].toFloat(), right, ltrb[3].toFloat())*/

            //设置起始偏移角度(即第一个扇区从哪个角度开始绘制)
            //chart.setInitialAngle(90);	

            //标签显示(隐藏，显示在中间，显示在扇区外面)
            chart.labelStyle=ChartEnum.SliceLabelStyle.INSIDE
            chart.labelPaint.color = Color.WHITE

            //标题
            chart.setTitle("饼图-Pie Chart","(XCL-Charts Demo)")

            chart.setTitleVerticalAlign(VerticalAlign.BOTTOM)

            chart.dataSet = chartData

            //激活点击监听
            //chart.showClikedFocus()

            //设置允许的平移模式
            //chart.enablePanMode();
            //chart.setPlotPanMode(XEnum.PanMode.HORIZONTAL);	

            //显示图例
            val legend = chart.plotLegend
            legend.isVisible=true
            legend.legendType = ChartEnum.LegendType.COLUMN
            legend.horizontalAlign = HorizontalAlign.RIGHT
            legend.verticalAlign = VerticalAlign.MIDDLE
            legend.isShowBox = true
        } catch (e: Exception) {
            // TODO Auto-generated catch block
            Log.e(TAG, e.toString())
        }
    }

    private fun chartDataSet() {
        /*
		//设置图表数据源		
		chartData.add(new PieData("HP","20%",20,(int)Color.rgb(155, 187, 90)));
		chartData.add(new PieData("IBM","30%",30,(int)Color.rgb(191, 79, 75),false));
		chartData.add(new PieData("DELL","10%",10,(int)Color.rgb(242, 167, 69)));
		//将此比例块突出显示
		chartData.add(new PieData("EMC","40%",40,(int)Color.rgb(60, 173, 213),false));
		*/
        chartData.add(PieData("closed", "9%", 9f, Color.rgb(155, 187, 90)))
        chartData.add(PieData("inspect", "3%", 3f, Color.rgb(191, 79, 75)))
        chartData.add(PieData("open", "76%", 76f, Color.rgb(242, 167, 69)))
        chartData.add(PieData("workdone", "6%", 6f, Color.rgb(60, 173, 213)))
        chartData.add(PieData("dispute", "6%", 6f, Color.rgb(90, 79, 88)))
    }

   /* override fun render(canvas: Canvas) {
        try {
            chart.render(canvas)
        } catch (e: Exception) {
            Log.e(TAG, e.toString())
        }
    }*/

    override fun run() {
        // TODO Auto-generated method stub
        try {
            chartAnimation()
        } catch (e: Exception) {
            Thread.currentThread().interrupt()
        }
    }

    private fun chartAnimation() {
        try {
            chart.dataSet = chartData
            val count = 360 / 10
            for (i in 1 until count) {
                Thread.sleep(40)
                chart.totalAngle = (10 * i).toFloat()

                //激活点击监听
                if (count - 1 == i) {
                    chart.totalAngle = 360f
                    //显示边框线，并设置其颜色
                    chart.arcBorderPaint.color = Color.YELLOW
                    chart.arcBorderPaint.strokeWidth = 3f
                }
                postInvalidate()
            }
        } catch (e: Exception) {
            Thread.currentThread().interrupt()
        }
    }

    /*
	 * 另一种动画
	private void chartAnimation()
	{
		  try {       
			 
			  	float sum = 0.0f;
			  	int count = chartData.size();
	          	for(int i=0;i< count ;i++)
	          	{
	          		Thread.sleep(150);
	          	
	          		ArrayList<PieData> animationData = new ArrayList<PieData>();
	        
	          		sum = 0.0f;
	          			          		
	          		for(int j=0;j<=i;j++)
	          		{            			            			
	          			animationData.add(chartData.get(j));
	          			sum = (float) MathHelper.getInstance().add(
	          									sum , chartData.get(j).getPercentage());	          			
	          		}   		          		
	          			          			          				          				          	
	          		animationData.add(new PieData("","",  MathHelper.getInstance().sub(100.0f , sum),
	          											  Color.argb(1, 0, 0, 0)));		          		
	          		chart.setDataSource(animationData);
	          	
	          		//激活点击监听
	    			if(count - 1 == i)
	    			{
	    				chart.ActiveListenItemClick();
	    				//显示边框线，并设置其颜色
	    				chart.getArcBorderPaint().setColor(Color.YELLOW);
	    				chart.getArcBorderPaint().setStrokeWidth(3);
	    			}
	    			
	          		postInvalidate();            				          	          	
	          }
			  
          }
          catch(Exception e) {
              Thread.currentThread().interrupt();
          }       
		  
	}
	*/
    @SuppressLint("ClickableViewAccessibility")
    override fun onTouchEvent(event: MotionEvent): Boolean {
        // TODO Auto-generated method stub		
        super.onTouchEvent(event)
        /*if (event.action == MotionEvent.ACTION_UP) {
            if (chart.selectHelper.isPlotClickArea(event.x, event.y)) {
                triggerClick(event.x, event.y)
            }
        }*/
        return true
    }

}